let currentEventId = null;
let currentReportId = null;
let originalContent = '';
let selectedPhotos = [];
let selectedPhotoDescriptions = [];

// 页面加载时获取事件信息

document.addEventListener('DOMContentLoaded', async function() {
    // 等待AuthManager初始化
    const checkAuth = () => {
        if (window.AuthManager) {
            initPage();
        } else {
            setTimeout(checkAuth, 100);
        }
    };
    checkAuth();
});

// 初始化页面
async function initPage() {
    // JWT认证检查
    if (!window.AuthManager || !AuthManager.isAuthenticated()) {
        showAccessDenied();
        return;
    }
    // 检查token有效性
    try {
        await AuthManager.verifyToken();
    } catch (e) {
        showAccessDenied();
        return;
    }
    const urlParams = new URLSearchParams(window.location.search);
    currentEventId = urlParams.get('eventId');
    if (currentEventId) {
        loadEventInfo();
        checkExistingReport();
        setupPhotoUpload();
    } else {
        showAlert('缺少事件ID参数', 'danger');
    }
}

// 显示访问被拒绝
function showAccessDenied() {
    document.body.innerHTML = '<div class="access-denied" style="text-align:center;padding:50px 20px;color:#6c757d;"><i class="bi bi-shield-exclamation" style="font-size:4rem;margin-bottom:20px;"></i><h3>访问被拒绝</h3><p>请先登录系统。</p><a href="/ercms/login" class="btn btn-primary">去登录</a></div>';
}

// 设置照片上传功能
function setupPhotoUpload() {
    // 新报告照片上传
    const photoInput = document.getElementById('photoInput');
    const photoUploadArea = document.getElementById('photoUploadArea');
    photoInput.addEventListener('change', handlePhotoSelect);
    setupDragAndDrop(photoUploadArea, photoInput);
    // 编辑模式照片上传
    const editPhotoInput = document.getElementById('editPhotoInput');
    const editPhotoUploadArea = document.getElementById('editPhotoUploadArea');
    editPhotoInput.addEventListener('change', handleEditPhotoSelect);
    setupDragAndDrop(editPhotoUploadArea, editPhotoInput);
}

// 设置拖拽上传
function setupDragAndDrop(uploadArea, fileInput) {
    uploadArea.addEventListener('dragover', function(e) {
        e.preventDefault();
        uploadArea.classList.add('dragover');
    });
    uploadArea.addEventListener('dragleave', function(e) {
        e.preventDefault();
        uploadArea.classList.remove('dragover');
    });
    uploadArea.addEventListener('drop', function(e) {
        e.preventDefault();
        uploadArea.classList.remove('dragover');
        const files = Array.from(e.dataTransfer.files);
        handleFiles(files, fileInput);
    });
    uploadArea.addEventListener('click', function() {
        fileInput.click();
    });
}

// 处理照片选择
function handlePhotoSelect(e) {
    const files = Array.from(e.target.files);
    handleFiles(files, e.target);
}

function handleEditPhotoSelect(e) {
    const files = Array.from(e.target.files);
    handleFiles(files, e.target);
}

// 处理文件
function handleFiles(files, input) {
    const imageFiles = files.filter(file => file.type.startsWith('image/'));
    if (imageFiles.length === 0) {
        showAlert('请选择图片文件', 'warning');
        return;
    }
    // 验证文件大小
    const maxSize = 10 * 1024 * 1024; // 10MB
    const validFiles = imageFiles.filter(file => file.size <= maxSize);
    if (validFiles.length !== imageFiles.length) {
        showAlert('部分文件超过10MB限制，已跳过', 'warning');
    }
    // 添加照片到预览
    validFiles.forEach(file => {
        addPhotoToPreview(file, input.id === 'editPhotoInput' ? 'edit' : 'new');
    });
}

// 添加照片到预览
function addPhotoToPreview(file, mode) {
    const reader = new FileReader();
    reader.onload = function(e) {
        const photoId = Date.now() + Math.random();
        const photoItem = {
            id: photoId,
            file: file,
            description: '',
            preview: e.target.result
        };
        if (mode === 'edit') {
            selectedPhotos.push(photoItem);
            renderEditPhotoPreview();
        } else {
            selectedPhotos.push(photoItem);
            renderPhotoPreview();
        }
    };
    reader.readAsDataURL(file);
}

// 渲染照片预览
function renderPhotoPreview() {
    const preview = document.getElementById('photoPreview');
    preview.innerHTML = selectedPhotos.map(photo => `
        <div class="photo-item" data-id="${photo.id}">
            <img src="${photo.preview}" alt="预览">
            <button class="photo-remove" onclick="removePhoto('${photo.id}')">
                <i class="bi bi-x"></i>
            </button>
            <div class="photo-description">
                <input type="text" placeholder="照片描述" 
                       onchange="updatePhotoDescription('${photo.id}', this.value)"
                       style="width: 100%; border: none; background: transparent; color: white; font-size: 12px;">
            </div>
        </div>
    `).join('');
}

// 渲染编辑模式照片预览
function renderEditPhotoPreview() {
    const preview = document.getElementById('editPhotoPreview');
    preview.innerHTML = selectedPhotos.map(photo => `
        <div class="photo-item" data-id="${photo.id}">
            <img src="${photo.preview}" alt="预览">
            <button class="photo-remove" onclick="removePhoto('${photo.id}')">
                <i class="bi bi-x"></i>
            </button>
            <div class="photo-description">
                <input type="text" placeholder="照片描述" 
                       onchange="updatePhotoDescription('${photo.id}', this.value)"
                       style="width: 100%; border: none; background: transparent; color: white; font-size: 12px;">
            </div>
        </div>
    `).join('');
}

// 移除照片
function removePhoto(photoId) {
    selectedPhotos = selectedPhotos.filter(photo => photo.id !== photoId);
    renderPhotoPreview();
    renderEditPhotoPreview();
}

// 更新照片描述
function updatePhotoDescription(photoId, description) {
    const photo = selectedPhotos.find(p => p.id === photoId);
    if (photo) {
        photo.description = description;
    }
}

// 加载事件信息
function loadEventInfo() {
    // 确保eventId是数字类型
    const eventId = parseInt(currentEventId);
    if (isNaN(eventId)) {
        showAlert('无效的事件ID', 'danger');
        return;
    }
    fetch(`/ercms/api/events/${eventId}`, {
        headers: AuthManager.getAuthHeaders()
    })
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP ${response.status}: ${response.statusText}`);
            }
            return response.json();
        })
        .then(data => {
            document.getElementById('eventId').textContent = data.id;
            document.getElementById('eventType').textContent = data.eventType ? data.eventType.name : '未知';
            document.getElementById('eventStatus').textContent = getStatusDisplay(data.responderStatus);
            document.getElementById('eventTime').textContent = formatDateTime(data.startTime);
            document.getElementById('eventLocation').textContent = data.location || '未指定';
            document.getElementById('eventDescription').textContent = data.description || '无描述';
        })
        .catch(error => {
            console.error('加载事件信息失败:', error);
            showAlert('加载事件信息失败: ' + error.message, 'danger');
        });
}

// 检查是否已有报告
function checkExistingReport() {
    // 确保eventId是数字类型
    const eventId = parseInt(currentEventId);
    if (isNaN(eventId)) {
        showAlert('无效的事件ID', 'danger');
        return;
    }
    fetch(`/ercms/api/completion/${eventId}`, {
        headers: AuthManager.getAuthHeaders()
    })
        .then(response => {
            if (!response.ok) {
                if (response.status === 404) {
                    // 没有找到报告，这是正常的
                    return { success: false, message: "未找到完成报告" };
                }
                throw new Error(`HTTP ${response.status}: ${response.statusText}`);
            }
            return response.json();
        })
        .then(data => {
            if (data.success && data.data && data.data.id) {
                // 已有报告，显示现有报告
                showExistingReport(data.data);
            } else {
                // 没有报告，显示新报告表单
                showNewReportForm();
            }
        })
        .catch(error => {
            console.error('检查现有报告失败:', error);
            showAlert('检查现有报告失败 ' + error.message, 'danger');
            // 出错时也显示新报告表单
            showNewReportForm();
        });
}

// 显示现有报告
function showExistingReport(report) {
    currentReportId = report.id;
    originalContent = report.content;
    document.getElementById('existingReportContainer').style.display = 'block';
    document.getElementById('newReportContainer').style.display = 'none';
    document.getElementById('reportContentDisplay').textContent = report.content;
    document.getElementById('reportTime').textContent = '提交时间: ' + formatDateTime(report.reportTime);
    document.getElementById('editReportContent').value = report.content;
    // 加载现有照片
    loadReportPhotos(report.id);
}

// 加载报告照片
function loadReportPhotos(reportId) {
    fetch(`/ercms/api/completion/${reportId}/photos`, {
        headers: AuthManager.getAuthHeaders()
    })
        .then(response => response.json())
        .then(data => {
            if (data.success && data.data) {
                renderExistingPhotos(data.data);
            }
        })
        .catch(error => {
            console.error('加载照片失败:', error);
        });
}

// 渲染现有照片
function renderExistingPhotos(photos) {
    const grid = document.getElementById('existingPhotosGrid');
    if (photos.length === 0) {
        grid.innerHTML = '<p class="text-muted">暂无照片</p>';
        return;
    }
    grid.innerHTML = photos.map(photo => `
        <div class="photo-card">
            <img src="/ercms/api/completion/photos/${photo.id}/file" alt="${photo.fileName}">
            <div class="card-body">
                <h6 class="card-title">${photo.fileName}</h6>
                <p class="card-text">${photo.description || '无描述'}</p>
                <p class="card-text"><small class="text-muted">上传时间: ${formatDateTime(photo.uploadTime)}</small></p>
                <button class="btn btn-sm btn-outline-danger" onclick="deletePhoto(${photo.id})">
                    <i class="bi bi-trash"></i> 删除
                </button>
            </div>
        </div>
    `).join('');
}

// 删除照片
function deletePhoto(photoId) {
    if (!confirm('确定要删除这张照片吗？')) {
        return;
    }
    fetch(`/ercms/api/completion/photos/${photoId}`, {
        method: 'DELETE',
        headers: AuthManager.getAuthHeaders()
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showAlert('照片删除成功', 'success');
            loadReportPhotos(currentReportId);
        } else {
            showAlert(data.error || '删除失败', 'danger');
        }
    })
    .catch(error => {
        console.error('删除照片失败:', error);
        showAlert('删除照片失败', 'danger');
    });
}

// 显示新报告表单
function showNewReportForm() {
    document.getElementById('existingReportContainer').style.display = 'none';
    document.getElementById('newReportContainer').style.display = 'block';
}

// 启用编辑模式
function enableEdit() {
    document.getElementById('viewMode').style.display = 'none';
    document.getElementById('editMode').style.display = 'block';
    document.getElementById('editReportContent').value = originalContent;
    selectedPhotos = []; // 清空选择的图片
    renderEditPhotoPreview();
}

// 取消编辑
function cancelEdit() {
    document.getElementById('viewMode').style.display = 'block';
    document.getElementById('editMode').style.display = 'none';
    document.getElementById('editReportContent').value = originalContent;
    selectedPhotos = []; // 清空选择的图片
    renderEditPhotoPreview();
}

// 保存报告修改
function saveReport() {
    const content = document.getElementById('editReportContent').value.trim();
    if (!content) {
        showAlert('报告内容不能为空', 'warning');
        return;
    }
    const formData = new FormData();
    formData.append('content', content);
    // 添加照片
    if (selectedPhotos.length > 0) {
        selectedPhotos.forEach(photo => {
            formData.append('photos', photo.file);
            formData.append('descriptions', photo.description || '');
        });
    }
    fetch(`/ercms/api/completion/${currentReportId}/with-photos`, {
        method: 'PUT',
        body: formData,
        headers: { 'Authorization': `Bearer ${AuthManager.getToken()}` }
    })
    .then(response => response.json())
    .then(data => {
        if (data.error) {
            showAlert(data.error, 'danger');
        } else if (data.success) {
            originalContent = content;
            document.getElementById('reportContentDisplay').textContent = content;
            document.getElementById('reportTime').textContent = '修改时间: ' + formatDateTime(data.data.reportTime);
            cancelEdit();
            showAlert('报告修改成功', 'success');
            // 重新加载照片
            loadReportPhotos(currentReportId);
        } else {
            showAlert('保存报告失败：未知错误', 'danger');
        }
    })
    .catch(error => {
        console.error('保存报告失败:', error);
        showAlert('保存报告失败', 'danger');
    });
}

// 提交新报告

document.getElementById('reportForm').addEventListener('submit', function(e) {
    e.preventDefault();
    const content = document.getElementById('reportContent').value.trim();
    if (!content) {
        showAlert('报告内容不能为空', 'warning');
        return;
    }
    // 确保eventId是数字类型
    const eventId = parseInt(currentEventId);
    if (isNaN(eventId)) {
        showAlert('无效的事件ID', 'danger');
        return;
    }
    const formData = new FormData();
    formData.append('eventId', eventId);
    formData.append('content', content);
    // 添加照片
    if (selectedPhotos.length > 0) {
        selectedPhotos.forEach(photo => {
            formData.append('photos', photo.file);
            formData.append('descriptions', photo.description || '');
        });
    }
    fetch('/ercms/api/completion/with-photos', {
        method: 'POST',
        body: formData,
        headers: { 'Authorization': `Bearer ${AuthManager.getToken()}` }
    })
    .then(response => {
        if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }
        return response.json();
    })
    .then(data => {
        if (data.error) {
            showAlert(data.error, 'danger');
        } else if (data.success) {
            showAlert('报告提交成功！事件状态已更新为完成', 'success');
            // 重新加载页面显示现有报告
            setTimeout(() => {
                checkExistingReport();
            }, 1000);
        } else {
            showAlert('提交报告失败：未知错误', 'danger');
        }
    })
    .catch(error => {
        console.error('提交报告失败:', error);
        showAlert('提交报告失败: ' + error.message, 'danger');
    });
});

// 显示状态文本
function getStatusDisplay(status) {
    const statusMap = {
        'PENDING': '待处理',
        'ASSIGNED': '已指派',
        'ACCEPTED': '已接受',
        'EN_ROUTE': '前往中',
        'ARRIVED': '已到达',
        'IN_PROGRESS': '处理中',
        'COMPLETED': '已完成',
        'RETURNING': '返回中',
        'CLOSED': '已关闭'
    };
    return statusMap[status] || status;
}

// 格式化日期时间
function formatDateTime(dateTimeStr) {
    if (!dateTimeStr) return '未知';
    const date = new Date(dateTimeStr);
    return date.toLocaleString('zh-CN');
}

// 显示提示消息
function showAlert(message, type) {
    const alertContainer = document.getElementById('alertContainer');
    const alertHtml = `
        <div class="alert alert-${type} alert-dismissible fade show" role="alert">
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    `;
    alertContainer.innerHTML = alertHtml;
    // 3秒后自动消失
    setTimeout(() => {
        const alert = alertContainer.querySelector('.alert');
        if (alert) {
            alert.remove();
        }
    }, 3000);
} 